<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Admin;
use app\admin\model\Memberlevel;
use app\admin\model\Membercoupon;
use app\admin\model\Store;
use app\admin\model\Image;
use app\admin\service\Member as MemberService;

use think\Request;

class Member extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['m_status'] = ['neq', 0];
        $this->defaultWhere = $defaultWhere;
        $this->defaultOrder = 'create_date DESC';

        // 会员等级
        $memberLevels = Memberlevel::where(['status' => 1])->select();
        $this->assign('memberLevels', $memberLevels);

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 门店
            $stores = Store::where([])->select();
            $this->assign('stores', $stores);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $info['img_url'] = $info['avatar'];

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();
            $data['avatar'] = $data['img_url'];
            if($data['balance']){
                $data['balance'] = $data['balance'] * 100;
            }
            if ($data['open_store_id']) {
                // 开通门店类型
                $data['open_store_type'] = 2;
                // 开通人
                $data['open_person'] = $this->admin->id;
            } else {
                $data['open_store_type'] = 1;
                $data['open_time'] = null;
                $data['end_time'] = null;
                $data['open_person'] = '';
            }

            if ($data['id']) {
                // Update data
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                $logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_update';
            } else {
                // Insert data
                $data['id'] = Helper::getUUID();
                $result = $model->save($data);
                $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_insert';
            }

            if($result !== false) {
                // 单图
                if(isset($data['img_id']) && !empty($data['img_id'])){
                    Image::where('id', $data['img_id'])->update(['related_id' => $data['id'], 'related_table' => 'member']);
                }

                // Query执行后的操作
                $model->$afterAction($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        $result = $model->where('id', $id)->update(['m_status' => 0]);
        if ($result !== false) {
            // 删除用户评论

            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            $item['sex'] = ($item['sex'] == 1) ? '男' : '女';
            $item['member_level'] = Memberlevel::where('id',  $item['member_level_id'])->value('name');
            // 余额
            $item['balance'] = $item['balance'] / 100;
            // 优惠券
            $item['count_coupon'] = Membercoupon::where(['member_id' => $item['id']])->count();
            if ($item['open_store_id'] && $item['open_store_type'] != 1) {
                // 开通门店
                $item['open_store'] = Store::where(['id' => $item['open_store_id']])->value('name');
                // 开通人
                $item['open_person'] = Admin::where(['id' => $item['open_person']])->value('name');
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['member_level_id']) && $param['member_level_id']){
            $where['member_level_id'] = $param['member_level_id'];
        }

        return $where;
    }

    /**
     * 检查用户名是否已存在
     */
    public function checkAccountNumber(){
        $model = model($this->model);
        $accountNumber = $this->request->param('account_number');
        $info = $model->where(['account_number' => $accountNumber])->field('account_number')->find();

        if($info){
            return json(['status' => 1]);
        }else{
            return json(['status' => 0]);
        }
    }

    /**
     * 导出数据
     */
    public function export(){
        $result = MemberService::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg'], url('admin/member/index'));
        }

        return redirect('admin/member/index');
    }

}